package com.baizhi.cmfz.shiro;

import com.baizhi.cmfz.dao.AdminDao;
import com.baizhi.cmfz.entity.Admin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Set;

public class AuthencationReal extends AuthorizingRealm {

	@Resource
	private AdminDao adminDao;

	/**
	 * 实现获得用户的授权信息
	 * @param principalCollection
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//		获取用户身份信息
		String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
//		使用用户名查询用户的角色信息和权限信息
		Set<String> role = adminDao.selectAdminRole(primaryPrincipal);
		Set<String> resource = adminDao.selectAdminResource(primaryPrincipal);
//		如果用户的角色信息和权限信息都不i为空
		if (role != null && resource != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			info.setRoles(role);
			info.setStringPermissions(resource);
			return info;
		}
		return null;
	}

	/**
	 *  实现获取用户的身份信息
	 * @param authenticationToken
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//		获取UsernamePasswordToken
		UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
//		得到用户的身份信息
		String username = token.getUsername();
//		数据库查询账号密码
		Admin admin = adminDao.selectAdminByNameAndPassword(username);
		if (admin != null) {
//			将信息放入session
			Session session = SecurityUtils.getSubject().getSession();
			session.setAttribute("admin",admin);
			return new SimpleAuthenticationInfo(admin.getAdminName(),admin.getAdminPassword(),this.getName());
		}
		return null;
	}
}
